<template>
  <view class="uni-container">
    <uni-forms ref="form" :value="formData" validate-trigger="submit" err-show-type="toast" label-position="top" label-width="200">
      <uni-forms-item name="postTitle" label="房源标题" required>
        <uni-easyinput placeholder="房源标题" v-model="formData.postTitle"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="postContent" label="房源描述">
        <uni-easyinput placeholder="房源描述"  v-model="formData.postContent"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="postSummary" label="房源摘要">
        <uni-easyinput placeholder="房源摘要" v-model="formData.postSummary"></uni-easyinput>
      </uni-forms-item>
<!--      <uni-forms-item name="postThumbnail" label="房源缩略图">
        <uni-easyinput placeholder="房源缩略图" v-model="formData.postThumbnail"></uni-easyinput>
      </uni-forms-item> -->
      <uni-forms-item name="postStatus" label="房源状态">
        <uni-data-checkbox v-model="formData.postStatus" :localdata="formOptions.postStatus_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="rentStart" label="承租日期" required>
        <uni-datetime-picker return-type="datetime"  v-model="formData.rentStart"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="rentEnd" label="承租结束日期"  required>
        <uni-datetime-picker return-type="datetime"  v-model="formData.rentEnd"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="landlordName" label="房东姓名" required>
        <uni-easyinput placeholder="房东姓名" v-model="formData.landlordName"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="landlordPhone" label="房东联系电话" required>
        <uni-easyinput placeholder="房东联系电话" v-model="formData.landlordPhone"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="price" label="月付价格">
        <uni-easyinput placeholder="月付价格" v-model="formData.price"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="area" label="面积" required>
        <uni-easyinput placeholder="面积" v-model="formData.area"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="roomCount" label="卧室数量" required>
        <uni-easyinput placeholder="卧室数量" v-model="formData.roomCount"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="toiletCount" label="洗手间数量">
        <uni-easyinput placeholder="洗手间数量" v-model="formData.toiletCount"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="deposit" label="押金" required>
        <uni-easyinput placeholder="押金" v-model="formData.deposit"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="contract" label="合同">
        <upload-image return-type="object" v-model="formData.contractList" @choose="uploadContract()" :filesList="formData.contractList" @uploadFiles="uploadContract()"></upload-image>
      </uni-forms-item>
      <uni-forms-item name="netFee" label="网费">
        <uni-easyinput placeholder="网费" v-model="formData.netFee"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="waterFee" label="水费">
        <uni-easyinput placeholder="水费" v-model="formData.waterFee"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="fireFee" label="燃气费">
        <uni-easyinput placeholder="燃气费" v-model="formData.fireFee"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="propertyFee" label="燃气费">
        <uni-easyinput placeholder="燃气费" v-model="formData.propertyFee"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="remark" label="备注">
        <uni-easyinput placeholder="备注" v-model="formData.remark"></uni-easyinput>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="margin-right: 10px" @click="submit">提交</button>
        <button type="primary" class="uni-button"  @click="addOrder">新增租客</button>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/postInfo.js';
  import UploadImage from "../../uni_modules/uni-file-picker/components/uni-file-picker/upload-image";


  const db = uniCloud.database();
  const dbCollectionName = 'postInfo';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.indexOf(key) > -1) {
        result[key] = validator[key]
      }
    }
    return result
  }

  export default {
    components: {UploadImage},
    data() {
      let formData = {
        "id": null,
        "postTitle": "",
        "postContent": "",
        "postSummary": "",
        "postThumbnail": "",
        "postStatus": 0,
        "rentStart": null,
        "rentEnd": null,
        "landlordName": "",
        "landlordPhone": "",
        "price": null,
        "area": "",
        "roomCount": null,
        "toiletCount": null,
        "deposit": null,
        "contract": '',
        "contractList": [],
        "netFee": null,
        "waterFee": null,
        "fireFee": null,
        "propertyFee": null,
        "remark": ""
      }
      return {
        formData,
        formOptions: {
          "postStatus_localdata": [
            {
              "text": "正在出租",
              "value": 0
            },
            {
              "text": "已经出租",
              "value": 1
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onLoad(e) {
      if (e.id) {
        const id = e.id
        this.formDataId = id
        this.formData.id = id
        this.getDetail(id)
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      addOrder() {
        uni.navigateTo({
          url: '/pages/order/add?postId=' + this.formData.id +'&postName='+this.formData.postTitle,
          events: {
            // 监听修改页面成功修改数据后, 刷新当前页面数据
            refreshData: () => {
              this.data = [];
              this.loadData()
            }
          }
        })

      },
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        this.formData.contract = JSON.stringify(this.formData.contractList);
        return this.$u.api.postInfo.update(this.formData).then((res) =>{
          uni.showToast({
            icon: 'none',
            title: '编辑成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        this.$u.api.postInfo.form(this.formDataId).then((resp) => {
          if (resp.code == '200') {
            this.formData = resp.data
            this.formData.contractList = JSON.parse(this.formData.contract)
			debugger
            if (!this.formData.contractList) {
              this.formData.contractList = [];
            }
          } else {
            this.$u.toast(resp.msg);
          }
        }).finally(
            () =>{
              uni.hideLoading()
            }
        )
      },
      uploadContract() {
        let url = "https://chenchao.pro/prod-api/common/upload";

        var that = this;
        uni.chooseImage({
          count: 1,
          sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album','camera'], //从相册选择
          success: function (res) {
            const tempFilePaths = res.tempFilePaths;
            //图片上传
            uni.uploadFile({
              url: url,
              filePath: tempFilePaths[0],
              name: 'file',
              file: {name: "file", uri: tempFilePaths[0]},
              header: {
                "Authorization": that.vuex_token
              },
              success: function (res) {
                const back = JSON.parse(res.data);
                that.formData.contractList.push(back)
				that.$forceUpdate()
              },
              fail: function (e) {
                console.log(e)
              }
            })
          },
          error : function(e){
            console.log(e);
          }
        });
      },

    }
  }
</script>

<style>
  .uni-container {
    padding: 15px;
  }

  .uni-input-border,
  .uni-textarea-border {
    width: 100%;
    font-size: 14px;
    color: #666;
    border: 1px #e5e5e5 solid;
    border-radius: 5px;
    box-sizing: border-box;
  }

  .uni-input-border {
    padding: 0 10px;
    height: 35px;

  }

  .uni-textarea-border {
    padding: 10px;
    height: 80px;
  }

  .uni-button-group {
    margin-top: 50px;
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    justify-content: center;
  }

  .uni-button {
    width: 184px;
    padding: 12px 20px;
    font-size: 14px;
    border-radius: 4px;
    line-height: 1;
    margin: 0;
  }
</style>
